import logging
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
import matplotlib.pyplot as plt


def hist_calculate(img, scale=256):
    assert img.ndim == 2
    hist = np.array([0] * scale)
    scale -= 1
    for pixel in np.nditer(img):
        index = int(pixel * scale)
        hist[index] += 1
    hist = hist / hist.sum()
    return hist


def hist_adjust(img, hist):
    assert img.ndim == 2
    assert hist.ndim == 1
    img = img.copy()
    hist = hist.copy()
    N = hist.shape[0] - 1
    for i in range(1,hist.shape[0]):
        hist[i] += hist[i-1]
    for pixel in np.nditer(img, op_flags=['readwrite']):
        index = int(pixel * N)
        pixel[...] = hist[index]
    return img

def hist_savetofile(hist,name):
    fig, ax = plt.subplots()
    left = np.array(range(0, hist.shape[0])) * 255 / len(hist)
    ax.bar(left=left, height=hist, width=0.8)
    ax.set_xlim(0, 255)
    pdf = PdfPages(name)
    pdf.savefig(fig)
    pdf.close()
    fig.clf()
    return


def show_gray_image(img):
    plt.imshow(img, cmap='Greys_r')
    plt.show()
    return
